# -*- coding: utf-8 -*-

import requests
import hashlib
import time
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime

url = "http://61.145.229.28:7902/sms/v2/std/get_balance"
userid = [
    "JS8619",
    "JS8620",
    "JS9015",
    "JS4855",
    "JS8528",
    "JS8529",
    "JS8595",
    "JS8596",
]
pwd = ["868125", "868125", "256310", "265210", "171328", "171329", "456888", "456777"]
# 获取时间戳
timestamp = time.strftime("%m%d%H%M%S", time.localtime())

# 定义列表集
uid_pwd = zip(userid, pwd)

# 定义输出空列表
result_uid = []
result_json = []


# 设置日志
log_file_path = "/data/python/log/get_sms_balance.log"  # 指定日志文件路径
logging.basicConfig(
    filename=log_file_path,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)


def connect_to_server():
    smtp_server = "smtp.mxhichina.com"
    port = 80
    sender_email = "noreply@pingcl.com"
    password = "p2q7hDokTA%BpmG"
    try:
        server = smtplib.SMTP(smtp_server, port)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(sender_email, password)
        logging.info("邮件服务器连接成功。")
        return server
    except Exception as e:
        logging.error("无法连接邮件服务器：" + str(e))
        raise


def Send_Mail(messages):
    # 获取当前日期和时间
    now = datetime.now()
    server = connect_to_server()

    sender_email = "noreply@pingcl.com"
    receiver_email = ["runfa.li@pingcl.com", "taoming.zhou@pingcl.com"]

    subject = f"日常-梦网短信详情({now})"
    # 将messages中的文本加粗，整个消息使用HTML格式
    message = messages

    email = MIMEMultipart()
    email["From"] = sender_email
    email["To"] = ", ".join(receiver_email)
    email["Subject"] = subject
    # 将邮件正文格式设置为HTML
    email.attach(MIMEText(message, "html"))

    try:
        server.send_message(email)
        server.quit()
        logging.info("邮件发送成功！\n")
    except Exception as e:
        logging.error("邮件发送失败：\n" + str(e))
        raise


def getBlance():
    for uid, upwd in uid_pwd:
        # 明文密码 MD5 加密
        tempPwd = uid.upper() + "00000000" + upwd + timestamp
        md5 = hashlib.md5()
        md5.update(tempPwd.encode("utf-8"))
        md5Pwd = md5.hexdigest()

        # 定义字典
        data = {
            "userid": uid,
            "pwd": md5Pwd,
            "timestamp": timestamp,
        }

        try:
            # 获取 json
            response = requests.post(url, data=data)
            result = response.json()
            result_uid.append(uid)
            result_json.append(result)
            logging.info("{} 获取成功！".format(uid))
        except Exception as e:
            logging.error("{} 获取失败！".format(uid) + str(e))
            raise
    return result_uid, result_json


result_uid, result_json = getBlance()
final_messages = []

for uid, result in zip(result_uid, result_json):
    if result["result"] == 0:
        if uid == "JS8619":
            sms_balance_8619 = int(result["balance"])
            msg = (
                "*新浪健康(生产账号) "
                + uid
                + " 短信余量为：{} 条*.<br>".format(sms_balance_8619)
            )
            final_messages.append(msg)
        if uid == "JS8620":
            sms_balance_8620 = int(result["balance"])
            msg = (
                "*新浪健康(服务账号) "
                + uid
                + " 短信余量为：{} 条*.<br>".format(sms_balance_8620)
            )
            final_messages.append(msg)
        if uid == "JS9015":
            sms_balance_9015 = int(result["balance"])
            msg = (
                "*爱问医生 " + uid + " 短信余量为：{} 条*.<br>".format(sms_balance_9015)
            )
            final_messages.append(msg)
        if uid == "JS4855":
            sms_balance_4855 = int(result["balance"])
            msg = (
                "*营销类爱问医生 "
                + uid
                + " 短信余量为：{} 条*.<br>".format(sms_balance_4855)
            )
            final_messages.append(msg)
        if uid == "JS8528":
            sms_balance_8528 = int(result["balance"])
            msg = (
                "*爱问健康 " + uid + " 短信余量为：{} 条*.<br>".format(sms_balance_8528)
            )
            final_messages.append(msg)
        if uid == "JS8529":
            sms_balance_8529 = int(result["balance"])
            msg = (
                "*营销类爱问健康 "
                + uid
                + " 短信余量为：{} 条*.<br>".format(sms_balance_8529)
            )
            final_messages.append(msg)
        if uid == "JS8595":
            sms_balance_8595 = int(result["balance"])
            msg = (
                "*爱问社区 " + uid + " 短信余量为：{} 条*.<br>".format(sms_balance_8595)
            )
            final_messages.append(msg)
        if uid == "JS8596":
            sms_balance_8596 = int(result["balance"])
            msg = (
                "*营销类爱问社区 "
                + uid
                + " 短信余量为：{} 条*.<br>".format(sms_balance_8596)
            )
            final_messages.append(msg)
    else:
        msg = "* " + uid + " 查询失败，错误码为：{}*".format(result["result"])
        final_messages.append(msg)


sum_blance = (
    sms_balance_8619,
    sms_balance_8620,
    sms_balance_9015,
    sms_balance_4855,
    sms_balance_8528,
    sms_balance_8529,
    sms_balance_8595,
    sms_balance_8596,
)

try:
    msg = "*总短信余量为：{} 条*.".format(sum(sum_blance))
    logging.info("总数统计成功！")
except Exception as e:
    logging.error("总数统计失败：" + str(e))

final_messages.append(msg)
# 将所有消息合并为一个字符串
final_message = "".join(final_messages)
messages = (
    "您好！<br>今天的梦网短信详情：<br>"
    + "<strong>{}</strong>".format(final_message)
    + "<br>请关注！"
)
print(messages)
Send_Mail(messages)
